
const Sequelize = require('sequelize')
const config = require('../config')
const sequelize = new Sequelize(
  'user_association',
  config.dbUser,
  config.dbPassword,
  {
    host: config.dbHost,
    port: config.dbPort,
    dialect: 'mysql',
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    timezone: '+08:00',
    // 请参考 Querying - 查询 操作符 章节
    operatorsAliases: false
  }
)

sequelize.authenticate().then(() => {
  console.log('Connection has been established successfully.')
}).catch(err => {
  console.error('Unable to connect to the database:', err)
})
// 商品
const Product = sequelize.define('product', {
  title: Sequelize.STRING
})
// 用户
const User = sequelize.define('user', {
  first_name: Sequelize.STRING,
  last_name: Sequelize.STRING
})
// 地址
const Address = sequelize.define('address', {
  type: Sequelize.STRING,
  line_1: Sequelize.STRING,
  line_2: Sequelize.STRING,
  city: Sequelize.STRING,
  state: Sequelize.STRING,
  zip: Sequelize.STRING
})
// 商品关联一个用户
Product.User = Product.belongsTo(User)
// 用户关联多个地址
User.Addresses = User.hasMany(Address)
// 也能用于 `hasOne`
sequelize.sync({ force: false }).then(() => {
  // Product.create(
  //   {
  //     title: 'Chair',
  //     user: {
  //       first_name: 'Mick',
  //       last_name: 'Broadstone',
  //       addresses: [
  //         {
  //           type: 'home0',
  //           line_1: '100 Main St.',
  //           city: 'fuzhou',
  //           state: 'TX',
  //           zip: '78704'
  //         },
  //         {
  //           type: 'home1',
  //           line_1: '100 Main St.',
  //           city: 'xiamen',
  //           state: 'TX',
  //           zip: '78704'
  //         }
  //       ]
  //     }
  //   },
  //   {
  //     include: [
  //       {
  //         association: Product.User,
  //         include: [User.Addresses]
  //       }
  //     ]
  //   }
  // )
  Product.findAndCountAll({
    include: [
      {
        association: Product.User,
        include: [User.Addresses]
      }
    ]
  }).then(products => {
    console.log(JSON.stringify(products))
  })
})
